/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as _ from "lodash"
import httpClient from "../httpclient"


export class Category {

  public id: string
  public name: number
  public search_keywords: string[]
  private image_url: string
  public position: number
  public children: Category[]

  public get imageUrl() {
    return this.image_url
  }

  public set imageUrl(imageUrl) {
    this.image_url = imageUrl
  }

  public get searchKeywords() {
    return this.search_keywords
  }

  public set searchKeywords(searchKeywords) {
    this.search_keywords = searchKeywords
  }
}

function transform(categories: Category[]): Category[] {
  return _.map(categories, category => {
    if (category.children) {
      category.children = transform(category.children)
    }
    return _.assign(new Category(), category)
  })
}


class CategoryQuery {
  private params = {}

  public parentId(parentId: string) {
    this.params["parent_id"] = parentId
    return this
  }

  public level(level: number) {
    this.params["level"] = level
    return this
  }

  public list(): Promise<Category[]> {
    return httpClient.get(`/v1/categories`, { params: this.params })
      .then(({ data }) => data)
      .then(transform)
  }
}

export class CategoryServiceV1 {
  public static getCategories() {
    return new CategoryQuery()
  }
}
